<template>
<el-card class="box-card">
  <div slot="header" class="clearfix">
    <span v-if="this.$route.query.id">试题修改</span>
    <span v-else>试题录入</span>
  </div>
  <div class="text item">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
      <el-form-item label="学科 :" prop="subjectID">
        <el-select v-model="form.subjectID" placeholder="请选择" class="select" @change="changeSubject">
          <el-option v-for="(item, index) in subjects" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目录 :" prop="catalogID">
        <el-select v-model="form.catalogID" placeholder="请选择" class="select">
          <el-option v-for="item in directorys" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="企业 :" prop="enterpriseID">
        <el-select v-model="form.enterpriseID" placeholder="请选择" class="select">
          <el-option v-for="item in companys" :key="item.id" :label="item.company" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="城市 :" prop="province">
        <el-select
          class="city"
          v-model="form.province"
          @keyup.enter="handleFilter"
          @change="handleProvince"
          filterable>
          <el-option
            v-for="item in citySelect.province"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
        <el-select
          class="city"
          v-model="form.city"
          @keyup.enter="handleFilter"
          filterable>
          <el-option
            v-for="item in citySelect.cityDate"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="方向 :" prop="direction">
        <el-select v-model="form.direction" placeholder="请选择" class="select">
          <el-option v-for="item in direction" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="题型 :" prop="questionType">
        <el-radio-group v-model="form.questionType">
          <el-radio v-for="item in questionType" :key="item.value" :label="item.value">{{item.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="难度 :" prop="difficulty">
        <el-radio-group v-model="form.difficulty">
          <el-radio :label="item.label" v-for="item in difficulty" :key="item.value"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题干 :" prop="question" style="height:260px">
        <quill-editor v-model="form.question" style="height:200px;" :options="editorOption" />
      </el-form-item>
      <el-form-item
        label="选项 :"
        prop="content"
        class="option_item"
        v-if="form.questionType === 1">
        <div
          class="option_item"
          style="width:2000px"
          v-for="(item, index) in option_items"
          :key="item.id">
          <el-radio-group v-model="radio">
            <el-radio :label="index" :checked="form.options[index].isRight" class="radioIndex">
              {{item}}：
            </el-radio>
          </el-radio-group>
          <el-input v-model="form.options[index].title" class="options"></el-input>&nbsp;
            <!--
            - action：必选参数，上传的地址：http://ttapi.research.itcast.cn/mp/v1_0/user/images
            - headers: 设置上传的请求头部。要携带token
            - name：上传的文件字段名。要与接口中要求保持一致。
            - show-file-list： 是否显示已上传文件列表
            - on-success：文件上传成功时的钩子。`function(response, file, fileList)`
            - before-upload: 上传之前对文件进行检测。
            -->
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="hSuccess"
            :before-upload="beforeAvatarUpload"
            style="width:100px;height:60px"
            @click.native="clickUpload(index)">
              <!-- 当上传成功之后，imageUrl就会有值，此时做预览
                给img设置了src后，显示图片内容的过程是异步的 ---- 并不是设了src后就可以立即看到图片的

                问：你怎么知道图片已经完成了加载？
              -->
              <el-image v-if="url[index]" :src="url[index]" class="avatar" @load="hLoadUploadImage" />
              <span v-else class="avatar-uploader-span">上传图片</span>
          </el-upload>
        </div>
        <el-button
          type="danger"
          :disabled="form.questionType === 1"
          v-if="form.questionType === 1">
           危险按钮
        </el-button>
      </el-form-item>
      <el-form-item label="选项 :" prop="content" class="option_item" v-else-if="form.questionType === 2">
        <div class="option_item" v-for="(item, index) in option_items" :key="item.id">
          <el-checkbox :label="index" :checked="form.options[index].isRight" class="checkIndex">
            {{item}}：
          </el-checkbox>
          <el-input v-model="form.options[index].title" class="options"></el-input>&nbsp;
          <el-upload
            class="avatar-uploader"
            action="http://ttapi.research.itcast.cn/mp/v1_0/user/images"
            :headers="headers"
            name="image"
            :show-file-list="false"
            :on-success="hSuccess"
            :before-upload="beforeAvatarUpload"
            style="width:100px;height:60px"
            @click.native="clickUpload(index)">
              <el-image v-if="url[index]" :src="url[index]" class="avatar" @load="hLoadUploadImage" />
              <span v-else class="avatar-uploader-span">上传图片</span>
          </el-upload>
        </div>
        <el-button type="danger" @click="ascii">危险按钮</el-button>
      </el-form-item>
      <el-form-item label="解析视频 :">
        <el-input v-model="form.videoURL"></el-input>
      </el-form-item>
      <el-form-item label="答案解析 :" prop="answer" style="height:260px">
          <quill-editor v-model="form.answer" style="height:200px" class="Text" :options="editorOption" />
      </el-form-item>
      <el-form-item label="题目备注 :">
        <el-input type="textarea" style="height:96px;width:400px" v-model="form.remarks"></el-input>
      </el-form-item>
      <el-form-item label="试题标签 :" style="width:400px">
        <el-select
          style="width:400px"
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择文章标签">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-if="this.$route.query.id"
          type="primary"
          @click="changeSubmit">
          确认修改
        </el-button>
        <el-button
          v-else type="primary"
          @click="onSubmit('ruleForm')">
          确认提交
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</el-card>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple as simpleSubjects } from '@/api/hmmm/subjects.js'
import { simple as itemDirectorys } from '@/api/hmmm/directorys.js'
import { simple as itemTags } from '@/api/hmmm/tags.js'
import { list } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
import { add, detail, update } from '@/api/hmmm/questions.js'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      rules: {
        subjectID: [
          { required: true, message: '请选择学科名称', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请填写题干', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业名称', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择城市', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'blur' }
        ]
      },
      form: {
        subjectID: '',
        catalogID: '',
        direction: '',
        enterpriseID: '',
        remarks: '',
        difficulty: '简单',
        questionType: 1,
        tags: [],
        answer: '',
        question: '',
        province: '',
        city: '',
        options: [
          { isRight: false, title: '' },
          { isRight: false, title: '' },
          { isRight: false, title: '' },
          { isRight: false, title: '' }
        ],
        videoURL: ''
      },
      index: '',
      option_items: ['A', 'B', 'C', 'D'],
      subjects: [],
      directorys: [],
      headers: {
        Authorization: `Bearer ${localStorage.getItem('tokenStr')}`
      },
      companys: [],
      citys: [],
      direction: direction,
      questionType: questionType,
      difficulty: difficulty,
      citySelect: {
        province: [],
        cityDate: []
      },
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      options: [],
      value: [],
      url: ['', '', '', ''],
      radio: ''
    }
  },
  created () {
    this.subjectLoad()
    this.companysLoad()
    this.getCityData()
    this.itemTagsLoad()
    // 监听route是否带有id
    if (this.$route.query.id) {
      this.getList(this.$route.query.id)
    }
  },
  watch: {
    $route (to, from) {
      console.log(1)
    }
  },
  methods: {
    // 加载学科列表
    async subjectLoad () {
      try {
        const { data: res } = await simpleSubjects()
        this.subjects = res
      } catch (err) {
        console.log(err)
      }
    },
    // 学科列表change事件,获取目录列表
    async changeSubject (id) {
      try {
        const { data: res } = await itemDirectorys({ subjectID: id })
        this.directorys = res
        console.log(this.directorys)
        this.form.catalogID = ''
      } catch (err) {
        console.log(err)
      }
    },
    // 获取企业列表
    async companysLoad () {
      try {
        const { data: res } = await list()
        this.companys = res.items
      } catch (err) {
        console.log(err)
      }
    },
    // 标签列表获取
    async itemTagsLoad () {
      try {
        const { data: res } = await itemTags()
        this.options = res
      } catch (err) {
        console.log(err)
      }
    },
    // 获取省
    getCityData () {
      this.citySelect.province = provinces()
    },
    // 选省获取到市
    handleProvince (e) {
      this.citySelect.cityDate = citys(e)
    },
    // 点击选项增加按钮增加选项,使用ascii码值
    ascii () {
      const arrOption = this.option_items[this.option_items.length - 1]
      const ascii = arrOption.charCodeAt() + 1
      const code = String.fromCharCode(ascii)
      this.option_items.push(code)
      this.form.options.push({ code: '', title: '', img: '', isRight: false })
      this.url.push('')
    },
    // 分别获取选项列表数据
    optionsGet () {
      var options = []
      if (this.form.questionType === 1) {
        var radio = document.querySelectorAll('.radioIndex .el-radio__original')
        var radioItems = this.option_items
        var titleRadio = this.form.options
        var imgRadio = this.url
        radio.forEach(function (value, index) {
          var radio = { code: '', title: '', img: '', isRight: false }
          radio.isRight = value.checked
          radio.code = radioItems[index]
          radio.title = titleRadio[index].title
          radio.img = imgRadio[index]
          console.log(radio)
          options.push(radio)
        })
        console.log(radio)
        return options
      } else if (this.form.questionType === 2) {
        var checkBox = document.querySelectorAll('.checkIndex .el-checkbox__original')
        var checkItems = this.option_items
        var titleCheck = this.form.options
        var imgCheck = this.url
        checkBox.forEach(function (value, index) {
          var checkBox = { code: '', title: '', img: '', isRight: false }
          checkBox.isRight = value.checked
          checkBox.code = checkItems[index]
          checkBox.title = titleCheck[index].title
          checkBox.img = imgCheck[index]
          console.log(checkBox)
          options.push(checkBox)
        })
        return options
      }
    },
    // 提交数据
    async onSubmit () {
      this.$refs.ruleForm.validate((valid) => {
        // 若表单验证不通过,直接返回
        if (!valid) {
          this.$message.error('*为必填项')
          return
        }
        // 验证表单是否选择了正确选项
        // if (this.form.questionType === '1' && !this.option || this.form.questionType === '2' && this.checkOption.length === 0) {
        //   this.$message.warning('请选择正确项')
        //   return
        // }
        // 如果是编辑页面解析视频/题目备注验证不可为空
        if (this.$route.query.id) {
          if (!this.form.videoURL.trim()) {
            this.$message.warning('试题编辑,视频不可为空或空字符串')
            return
          }
          if (!this.form.remarks.trim()) {
            this.$message.warning('试题编辑,题目备注不可为空或空字符串')
            return
          }
        }
        var requstion = {}
        const subjectID = this.form.subjectID
        const catalogID = this.form.catalogID
        const enterpriseID = this.form.enterpriseID
        const province = this.form.province
        const city = this.form.city
        const direction = this.form.direction
        const questionType = this.form.questionType.toString()
        const difficulty = this.form.difficulty
        const question = this.form.question
        const videoURL = this.form.videoURL
        const answer = this.form.answer
        const remarks = this.form.remarks
        const tags = this.form.tags.join(',')
        const options = this.optionsGet()
        requstion = { subjectID, catalogID, enterpriseID, province, city, direction, questionType, difficulty, question, options, videoURL, answer, remarks, tags }
        console.log(requstion)
        this.$router.push('/questions/list')
        this.$message.success('提交成功!')
        add(requstion)
      })
    },
    hSuccess (res, file) {
      console.log('上传成功,从后端返回的数据是', res, file)
      this.$set(this.url, this.index, res.data.url)
      console.log(this.url)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 上传图片成功钩子
    hLoadUploadImage () {
      this.$message.success('你上传一直可以的')
    },
    // 点击上传获取下角标
    clickUpload (index) {
      this.index = index
      console.log(this.index)
    },
    // 数据回填
    async getList (id) {
      try {
        const { data: res } = await detail({ id })
        console.log(res)
        const resOptions = res.options
        const resTags = res.tags.split(',')
        resOptions.forEach(function (value, index) {
          if (value.isRight === 0) {
            value.isRight = false
          } else {
            value.isRight = true
          }
          // value.isRight = Boolean(value.isRight)
          // if (value.isRight === true) {
          //   this.radio = index
          // }
        })
        const optionsRadio = res.options
        console.log(optionsRadio)
        optionsRadio.forEach((value, index) => {
          if (value.isRight === true) {
            this.radio = index
          }
        })
        this.form = res
        this.form.questionType = Number(res.questionType)
        this.form.tags = resTags
        this.difficulty.forEach((val, index) => {
          if (val.value === Number(res.difficulty)) {
            this.form.difficulty = val.label
          } else {
            console.log(res.difficulty)
            console.log(val.value)
          }
        })
        this.subjectGet()
      } catch (err) {
        this.$message.error('数据出错!')
      }
    },
    // 提交修改
    async changeSubmit () {
      this.form.questionType = toString(this.form.questionType)
      this.form.tags = toString(this.form.tags)
      try {
        await update(this.form)
        this.$message.success('我好了!!!!!')
      } catch (err) {
        console.log(err)
      }
    },
    // 数据回填以后更新目录
    async subjectGet () {
      const id = this.form.subjectID
      try {
        const { data: res } = await itemDirectorys({ subjectID: id })
        this.directorys = res
      } catch (err) {
        console.log(err)
        this.$message.error('出错啦!')
      }
    }
  }
}
</script>

<style scoped lang='scss'>
  body {
    margin: 0;
    padding: 0;
}
.box-card {
  margin: 20px 20px 20px;
}
.el-card__body {
  padding: 20px;
}
.text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }
  .select {
    width: 400px;
  }
  .city {
    width: 197px;
    margin-right: 6px;
  }
  .options {
    width: 240px;
  }
  .option_item {
    // overflow: hidden;
    // width: 1000px;
    padding-bottom: 20px;
    line-height: 1;
  }
  .option_item .el-radio {
    margin: 0;
  }
  .Text {
    height: 239px;
  }
  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    text-align: center;
    margin: 0;
    width: 100px;
    height: 60px;
    cursor: pointer;
    overflow: hidden;
    display: inline-block;
    vertical-align: middle;
  }
  .avatar-uploader .el-upload {
    width: 100%;
    height: 100%;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-span {
    font-size: 15px;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 60px;
    display: block;
  }
</style>
